package com.cyandpos.pad.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cyandpos.pad.R;
import com.cyandpos.pad.common.commondata.BaseResponse;
import com.cyandpos.pad.common.commondata.Constant;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.common.commondata.SktConfigIdCrmConstant;
import com.cyandpos.pad.common.netmanager.PosHttpManager;
import com.cyandpos.pad.common.swipemanager.SwipeCardCommon;
import com.cyandpos.pad.http.OkHttpUtils;
import com.cyandpos.pad.login.configs.GetConfigs;
import com.cyandpos.pad.pay.adapter.CardCouponPayAdapter;
import com.cyandpos.pad.pay.listenter.MyClickListener;
import com.cyandpos.pad.pay.presenter.PayCardCouponPresenter;
import com.cyandpos.pad.pay.view.IPayCardCouponView;
import com.cyandpos.pad.posdata.CardCouponItem;
import com.cyandpos.pad.posdata.ConsumeCrmPayData;
import com.cyandpos.pad.posdata.Payment;
import com.cyandpos.pad.posdata.QueryMemberRequest;
import com.cyandpos.pad.posdata.YhqCardItem;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.PayUtil;
import com.cyandpos.pad.utils.ToastUtils;
import com.cyandpos.pad.utils.log.LogUtils;
import com.cyandpos.pad.utils.view.InputNumberDialogCommon;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;

public class CardCouponPayActivity extends BaseActivity implements View.OnClickListener, IPayCardCouponView, SwipeCardCommon.DoAfterSwipeCard {
    @BindView(R.id.rl_close)
    RelativeLayout rl_close;
    @BindView(R.id.yhq_list)
    ListView yhqLv;
    @BindView(R.id.yhq_needPay)
    TextView yhqNeedPay;//应收金额
    @BindView(R.id.yhq_pay)
    TextView yhqPay;//实付金额
    @BindView(R.id.btn_yhqOk)
    Button btnYhqOk;
    @BindView(R.id.iv_member)
    ImageView iv_member;
    private CardCouponPayAdapter adapter ;
    private List<CardCouponItem> useCouponList;//用券列表
    private List<CardCouponItem> cardCouponList ;//卡券列表
    private int  mSelectedId = -1;
    private int  payedType = -1;

    private AlertDialog mDialog;//会员识别弹dialog
    int payedMoney = 0;//优惠券当前已经付款金额
    public PayCardCouponPresenter netPresenter;
    private ProgressDialog dialog;//网络请求dialog
    @Override
    protected int getLayoutId() {
        return R.layout.activity_cardcoupon_pay;
    }

    @Override
    protected void initData() {
        initView();
        if(ErpCommonData.ticketInfo.getCardCouponList().size()>0){
            cardCouponList.clear();
            cardCouponList.addAll(ErpCommonData.ticketInfo.getCardCouponList());
            adapter.notifyDataSetChanged();
            updateCouponTotalPayMoney();
        }else{
            PayUtil.showQueryMemberDialog(CardCouponPayActivity.this, Constant.MEMBER_IDENTIFYING_CARDCOUPON);
        }
    }

    private void initView() {
        useCouponList = new ArrayList<>();
        cardCouponList = new ArrayList<>();
        netPresenter = new PayCardCouponPresenter(this);
        dialog = new ProgressDialog(this);
        Intent intent = getIntent();
        mSelectedId = intent.getIntExtra("SelectedId",-1);
        payedType = intent.getIntExtra("PayType",-1);
        yhqNeedPay.setText(MoneyUtils.getMoneyStr(ErpCommonData.ticketInfo.getTotalMoney() - ErpCommonData.ticketInfo.getHasPayed()));
        updateCouponTotalPayMoney();
        btnYhqOk.setOnClickListener(this);
        adapter = new CardCouponPayAdapter(this,cardCouponList,mListener);
        yhqLv.setAdapter(adapter);
        adapter.setUseOnClickListener(new CardCouponPayAdapter.UseOnClickListener() {
            @Override
            public void onClickListener(int position) {
                CardCouponItem selectItem =adapter.getItem(position);
                showCardCouponInputMoney(selectItem,adapter);
            }
        });
        yhqLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
                CardCouponItem selectItem =adapter.getItem(position);
                showCardCouponInputMoney(selectItem,adapter);
            }
        });

        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                useCouponList.clear();
                finish();
            }
        });
        iv_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                                //1.确认是否已有有券列表
                againSwipeCardHandleUsedCouponList();
                PayUtil.showQueryMemberDialog(CardCouponPayActivity.this,Constant.MEMBER_IDENTIFYING_CARDCOUPON);
            }
        });

    }


    private void againSwipeCardHandleUsedCouponList() {
        useCouponList.clear();
        for(CardCouponItem item :cardCouponList){
            if(item.getUsedMoney()!=0  ){//使用了此券
                useCouponList.add(item);
            }
        }
    }


    private MyClickListener mListener = new MyClickListener() {
        @Override
        public void myOnClick(int position, View v) {
            CardCouponItem selectItem =adapter.getItem(position);
            //当前券最大可使用金额
            int canUseMoney = selectItem.getBalance() < selectItem.getLimitMoney()? selectItem.getBalance():selectItem.getLimitMoney();
            //当前交易剩余应付金额
            int surplusPayM = ErpCommonData.ticketInfo.getTotalMoney() - ErpCommonData.ticketInfo.getHasPayed();
            //卡券已付金额
            int couponPayedM = 0;
            for(CardCouponItem item :cardCouponList){
                if(item.getUsedMoney()!=0  &&
                        ((item.getCardId() == selectItem.getCardId() && item.getCouponType()!=selectItem.getCouponType())
                                || item.getCardId() != selectItem.getCardId()
                        )){//使用了此券
                    couponPayedM += item.getUsedMoney();
                }
            }
            //卡券剩余最大应付金额
            int couponSurplusPaym = surplusPayM - couponPayedM;
            if(canUseMoney <= couponSurplusPaym){
                selectItem.setUsedMoney(canUseMoney);
                adapter.notifyDataSetChanged();
            }else{
                selectItem.setUsedMoney(couponSurplusPaym);
                adapter.notifyDataSetChanged();
            }
            updateCouponTotalPayMoney();
        }
    };

    private void updateCouponTotalPayMoney() {
        int couponPayedM = 0;
        for(CardCouponItem item :cardCouponList){
            if(item.getUsedMoney()!=0 ){//使用了此券
                couponPayedM += item.getUsedMoney();
            }
        }
        yhqPay.setText(MoneyUtils.getMoneyStr(couponPayedM));
    }

    private void showCardCouponInputMoney(final CardCouponItem selectItem, final CardCouponPayAdapter adapter ) {
        //当前券最大可使用金额
        int canUseMoney = selectItem.getBalance() < selectItem.getLimitMoney()? selectItem.getBalance():selectItem.getLimitMoney();
        //当前交易剩余应付金额
        int surplusPayM = ErpCommonData.ticketInfo.getTotalMoney() - ErpCommonData.ticketInfo.getHasPayed();
        //卡券已付金额(除去当前券已付金额)
        int couponPayedM = 0;
        for(CardCouponItem item :cardCouponList){
            if(item.getUsedMoney()!=0  &&
                    ((item.getCardId() == selectItem.getCardId()
                            && item.getCouponType()!=selectItem.getCouponType())
                            || item.getCardId() != selectItem.getCardId()
                    ) ){//使用了此券
                couponPayedM += item.getUsedMoney();
            }
        }
        //卡券剩余最大应付金额
        int couponSurplusPaym = surplusPayM - couponPayedM;
        final int currentCouponMaxPay = canUseMoney >= couponSurplusPaym ? couponSurplusPaym:canUseMoney;
        InputNumberDialogCommon inputNumberDialogCommon= InputNumberDialogCommon.getInputNumberDialogCommon(CardCouponPayActivity.this, new InputNumberDialogCommon.InputDialogOnSubmitClickListener() {
            @Override
            public void InputDialogOnSubmitClick(String content) {
                if(!CommonUtils.isNumber(content)){
                    ToastUtils.showMsg("请输入正确的金额！");
                }else{
                    try{
                        int inputMoney =MoneyUtils.getMoneyInt(content);
                        if(inputMoney <= currentCouponMaxPay){
                            selectItem.setUsedMoney(inputMoney);
                            adapter.notifyDataSetChanged();
                        }else{
                            selectItem.setUsedMoney(currentCouponMaxPay);
                            adapter.notifyDataSetChanged();
                            ToastUtils.showMsg("当前需支付金额为【"+MoneyUtils.getMoneyStr(currentCouponMaxPay)+"】");
                        }
                        updateCouponTotalPayMoney();
                    }catch (Exception e){
                        ToastUtils.showMsg("请输入正确的金额！");
                    }
                }
            }
        });
        inputNumberDialogCommon.setEtText(MoneyUtils.getMoneyStr(currentCouponMaxPay));
        inputNumberDialogCommon.setIsCanInputPoint(true);
        inputNumberDialogCommon.setIsCanInputClear(true);
        inputNumberDialogCommon.setTitle("使用金额");
        inputNumberDialogCommon.setContent("请输入使用金额");
        inputNumberDialogCommon.setEtHint("请输入使用金额");
        inputNumberDialogCommon.showDialog(false);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_yhqOk:{
                int totalCouponPayMoney = 0;//券使用总金额
                useCouponList.clear();
                for(CardCouponItem item :cardCouponList){
                    if(item.getUsedMoney()!=0  ){//使用了此券
                        totalCouponPayMoney +=item.getUsedMoney();
                        useCouponList.add(item);
                    }
                }

                if(totalCouponPayMoney > 0 ){
                    if(!GetConfigs.isTradeCutPayment()){//结账时扣款
                        //1.请求同步接口
                        ErpCommonData.ticketInfo.getCardCouponList().clear();
                        ErpCommonData.ticketInfo.getCardCouponList().addAll(useCouponList);
                        setResult(Constant.YHQ_Back_Pay_ResultID, null);
                        finish();
                    }else{//立即扣款
                        if(totalCouponPayMoney <=(ErpCommonData.ticketInfo.getTotalMoney() - ErpCommonData.ticketInfo.getHasPayed())){
                            //1.请求Consume扣款接口
                            reqCardCouponConsume();
                        }else{
                            ToastUtils.showMsg("付款金额大于应付金额！");
                        }
                    }
                }else{
                    ToastUtils.showMsg( "券使用金额为零！");
                }
            }
            break;
            default:
                break;
        }
    }

    private void reqCardCouponConsume() {
        ErpCommonData.ticketInfo.getCardCouponList().clear();
        ConsumeCrmPayData payData=new ConsumeCrmPayData();
        payData.setOrderno(ErpCommonData.ticketInfo.getOrderNo());
        payData.setCode(mSelectedId +"");
        payData.setType(payedType);
        payData.setGuid(UUID.randomUUID().toString());
        ArrayList<YhqCardItem> list=new ArrayList<>();
        for (CardCouponItem item:useCouponList){
            YhqCardItem cardItem=new YhqCardItem();
            cardItem.setCardId(item.getCardId());
            cardItem.setCardCode(item.getCardCode());
            cardItem.setUsedMoney(MoneyUtils.getMoneyStr(item.getUsedMoney()));
            cardItem.setCouponType(item.getCouponType());
            list.add(cardItem);
            ErpCommonData.ticketInfo.getCardCouponList().add(item);
        }
        payData.setYhqCard(list);
        PosHttpManager.ConsumeCrmPay(payData, new OkHttpUtils.ResultCallback() {
            @Override
            public void onSuccess(JsonObject response) {
                BaseResponse<BaseResponse> baseResponse = BaseResponse.fromJson(response.toString(), BaseResponse.class);
                if(baseResponse.getCode().equals("0")){
                    ToastUtils.showMsg("优惠券扣款成功！");
                    int totalCouponPayMoney = 0;
                    for (CardCouponItem item : useCouponList){
                        ErpCommonData.ticketInfo.getCardCouponList().add(item);
                        totalCouponPayMoney += item.getUsedMoney();
                    }
                    //生成付款方式
                    Payment payment = getCardCouponPayment();
                    payment.setPayAmount(MoneyUtils.getMoneyStr(totalCouponPayMoney));
                    setResult(Constant.YHQ_Back_Pay_ResultID, null);
                    finish();
                }else{
                    ToastUtils.showMsg( "优惠券扣款失败，"+baseResponse.getMsg());
                    if (TextUtils.isEmpty(baseResponse.getTips())){

                    }else {

                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtils.showMsg( "优惠券扣款失败,"+msg);
            }
        });


    }

    private Payment getCardCouponPayment() {
        if (ErpCommonData.ticketInfo == null)
            return null;
        Payment payMent = new Payment(Payment.SKFS_YHQK);
        payMent.setPayCode(9999);
        payMent.setPayName("电子卡券");
        ErpCommonData.ticketInfo.getPayList().add(payMent);
        return payMent;
    }

    /**
     * 刷卡结果
     * @param isSuccess
     * @param content
     * @param handleId
     */
    @Override
    public void doAfterSwipeCard(boolean isSuccess, String content, int handleId) {
        LogUtils.d("刷卡的结果为：" + content);
        switch (handleId) {
            case Constant.YHQ_SWIPECARD_HANDLEID: {
                if(isSuccess){
                    if (!content.equals("")) {
                        if(ErpCommonData.loadConfig.getSkt().getLength_verify_membercard()>0){
                            showVerifiedCodeDialog(content,SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SWIPE);//需要输入验证码
                        }else{
                            getCardCoupon(SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SWIPE,content,"");
                        }
                    }else{
                        ToastUtils.showMsg( "刷卡失败，请重试！");
                    }
                }else{
                    ToastUtils.showMsg("取消刷卡");
                }
            }
            break;
            default:
                break;
        }
    }

    private void getCardCoupon(int type,String conValue, String verifiedCode) {
        QueryMemberRequest param = new QueryMemberRequest();
        param.setCondType(type);
        param.setCondValue(conValue);
        param.setCodedCouponType(2);
        param.setServerBillId(Integer.parseInt(ErpCommonData.ticketInfo.getServerBillId()));
        param.setSktno(ErpCommonData.sktno);
        param.setVerifyCode(verifiedCode);
        param.setPassword("");
        param.setCardCodeToCheck("");
        param.setCodedCouponCode("");
        netPresenter.yhqkRequest(param);
    }

    private void showVerifiedCodeDialog(final String conValue,final int type) {
        AlertDialog.Builder dialogBank = new AlertDialog.Builder(CardCouponPayActivity.this);
        View view = getLayoutInflater().inflate(R.layout.dialog_yhq_payactivity, null);
        dialogBank.setView(view);
        final EditText et1 = view.findViewById(R.id.dialog_et);//储值卡卡号后四位
        dialogBank.setTitle("请输入验证码");
        PayUtil.showSoftKeyboard(et1,CardCouponPayActivity.this);
        dialogBank.setNegativeButton("取消",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String content = et1.getText().toString().trim();
                if(content.equals("") || content==null){
                    ToastUtils.showMsg( "请输入验证码");
                    return;
                }
                if(content.length() >0 && content.length()==ErpCommonData.loadConfig.getSkt().getLength_verify_membercard()){
                    dialog.dismiss();
                    getCardCoupon(type,conValue,content);
                }else{
                    ToastUtils.showMsg( "输入验证码错误！");
                }

            }
        }).create();
        dialogBank.setCancelable(false);
        dialogBank.show();
    }


    @Override
    public void showProgress(String msg) {
        if (dialog.isShowing()) {
            dialog.setMessage(msg);
        } else {
            dialog.setMessage(msg);
            dialog.show();
        }
    }

    @Override
    public void dismissProgress() {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void showLoadFailureMsg(String msg, int requestHandId) {
        ToastUtils.showMsg(msg);
    }

    @Override
    public void yhqkRequestData(ArrayList<CardCouponItem> yhqList) {
        if(yhqList.size()>0){
            if(cardCouponList.size()>0){//之前已经有使用的券
                for(CardCouponItem waitCoupon :yhqList){
                    boolean isExistSame = false;
                    for(CardCouponItem usedCoupon :cardCouponList){
                        if(waitCoupon.getCardId() == usedCoupon.getCardId()
                                && waitCoupon.getCouponType() == usedCoupon.getCouponType()){
                            isExistSame = true;
                            break;
                        }
                    }
                    if(!isExistSame){//不存在加入到显示列表
                        cardCouponList.add(waitCoupon);
                    }
                }
                adapter.notifyDataSetChanged();
            }else{
                cardCouponList.addAll(yhqList);
                adapter.notifyDataSetChanged();
            }

        }else{
            ToastUtils.showMsg("此会员卡中无可用优惠券！");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK)
            return;
        switch (requestCode){
            case Constant.YHQ_SCAN_HANDLEID:  //卡券扫码识别
                Bundle extras = data.getExtras();
                String content = extras.getString("Code");
                if (TextUtils.isEmpty(content))
                    return;
                if(ErpCommonData.loadConfig.getSkt().getLength_verify_membercard()>0){
                    showVerifiedCodeDialog(content, SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SCAN);//需要输入验证码
                }else{
                    getCardCoupon(SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SCAN,content,"");
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void QuickResult(String content ,int type){
        if(ErpCommonData.loadConfig.getSkt().getLength_verify_membercard()>0){
            showVerifiedCodeDialog(content,type);//需要输入验证码
        }else{
            getCardCoupon(type,content,"");
        }
    }
}
